package com.zcj.test.gallery;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;


public class ImageDetailActivity extends AppCompatActivity {
    private static final String TAG = "ImageDetailActivity";
    private static final String IMAGE_CACHE_DIR = "images";
    private int mCurrentPosition = 0;
    private ImagePagerAdapter mAdapter;
    private ImageFetcher mImageFetcher;
    private TextView imgpreTvTitle;
    private HackyViewPager mPager;
    private Toolbar toolbar;
    private LinearLayout layoutTitle;
    private List<String> imageUrl = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_imgpre);
        toolbar = (Toolbar) findViewById(R.id.imgpre_ll_title);
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.mipmap.ic_back);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        setTitle("");
        initFindView();
        init();
        initData();
    }

    private void initData() {
        imageUrl.add("http://img4.duitang.com/uploads/item/201309/20/20130920232939_SiEnF.thumb.600_0.jpeg");
        imageUrl.add("http://img.article.pchome.net/00/56/35/09/pic_lib/wm/fengjing1.jpg");
        imageUrl.add("http://cdn.duitang.com/uploads/item/201206/06/20120606174351_T2hVf.jpeg");
        imageUrl.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1498124381801&di=37068596384260055e2b74ae1ad8c7a2&imgtype=0&src=http%3A%2F%2Fwww.91zhuti.com%2Fuploads%2Fallimg%2F140311%2F4-1403111640520-L.jpg");
        imageUrl.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1498124381800&di=68f6e062d2f9c2ee1f3752f51aff54d1&imgtype=0&src=http%3A%2F%2Ff2.dn.anqu.com%2Fdown%2FMzBlNw%3D%3D%2Fallimg%2F1401%2F54-140110104333.jpg");
        imageUrl.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1498124381800&di=d536dee2a049048935f4dcf5d1d97b0a&imgtype=0&src=http%3A%2F%2Fimg.51ztzj.com%2Fupload%2Fimage%2F20140319%2Fsj20140320019_279x419.jpg");
        imageUrl.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1498124381798&di=5bc815262b82f89f3f641130361bb167&imgtype=0&src=http%3A%2F%2Fimgm.cnmo-img.com.cn%2Fappimg%2Fscreenpic%2Fmiddle%2F788%2F787435.jpg");
        imageUrl.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1498124381797&di=7cb4cb1ff3795374b873d17865710bb2&imgtype=0&src=http%3A%2F%2Fcdnq.duitang.com%2Fuploads%2Fitem%2F201412%2F13%2F20141213120059_WAWSF.jpeg");
        imageUrl.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1498124381797&di=444eb3320f5050a64ff5561d236b47cd&imgtype=0&src=http%3A%2F%2Fi6.download.fd.pchome.net%2Ft_320x520%2Fg1%2FM00%2F05%2F05%2FoYYBAFIJjWWIHPHaAAZAuAvbOo8AAAxmgHWNZEABkDQ571.jpg");
        imageUrl.add("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1498124381796&di=55b833edfd4f976245d3bcdfe2713a45&imgtype=0&src=http%3A%2F%2Fp1.wmpic.me%2Farticle%2F2016%2F07%2F11%2F1468228089_NilhVNew.jpg");
        setTitle();
        setmAdapter();
    }

    @Override
    public void onBackPressed() {
        Intent intent = new Intent();
        String filePath = null;
        if (imageUrl.size() != 0) {
            filePath = imageUrl.get(mCurrentPosition);
        }
        intent.putExtra("filePath", filePath);
        intent.putExtra("position", mCurrentPosition);
        setResult(Activity.RESULT_OK, intent);
        finish();
        super.onBackPressed();
    }

    public void chageTitleStatus() {
        if (layoutTitle.getVisibility() == View.VISIBLE) {
            layoutTitle.setVisibility(View.GONE);
        } else {
            layoutTitle.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        mImageFetcher.setExitTasksEarly(false);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mImageFetcher.setExitTasksEarly(true);
        mImageFetcher.flushCache();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mImageFetcher.closeCache();
    }

    private void initFindView() {
        imgpreTvTitle = (TextView) findViewById(R.id.title);
        mPager = (HackyViewPager) findViewById(R.id.imgpre_vp);
        layoutTitle = (LinearLayout) findViewById(R.id.imgpre_title);
    }

    private void init() {
        final DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        final int height = displayMetrics.heightPixels;
        final int width = displayMetrics.widthPixels;
        final int longest = (height > width ? height : width) / 2;
        ImageCache.ImageCacheParams cacheParams =
                new ImageCache.ImageCacheParams(this, IMAGE_CACHE_DIR);
        cacheParams.setMemCacheSizePercent(0.20f); // Set memory cache to 25% of app memory
        mImageFetcher = new ImageFetcher(this, longest);
        mImageFetcher.addImageCache(getFragmentManager(), cacheParams);
        mImageFetcher.setImageFadeIn(false);
    }


    private void setmAdapter() {
        mAdapter = new ImagePagerAdapter(getSupportFragmentManager(), imageUrl.size());
        mPager.setAdapter(mAdapter);
        mPager.setCurrentItem(mCurrentPosition, false);
        mPager.setOffscreenPageLimit(1);
        mPager.setPageMargin((int) getResources().getDimension(R.dimen.margin_side));
        mPager.addOnPageChangeListener(new MyListener());
    }

    public ImageFetcher getImageFetcher() {
        return mImageFetcher;
    }


    public void setTitle() {
        imgpreTvTitle.setText((mCurrentPosition + 1) + "/" + imageUrl.size());
    }


    private class ImagePagerAdapter extends FragmentStatePagerAdapter {
        private FragmentManager fm;
        private int size;

        public ImagePagerAdapter(FragmentManager fm, int size) {
            super(fm);
            this.fm = fm;
            this.size = size;
        }


        @Override
        public int getCount() {
            return size;
        }

        @Override
        public Fragment getItem(int position) {
            Log.d(TAG, "getItem: position " + position);
            String path = imageUrl.get(position);
            Log.d(TAG, "getItem: -----------" + path);
            ImageDetailFragment fragment = ImageDetailFragment.newInstance(path);
            return fragment;
        }
    }


    private class MyListener implements ViewPager.OnPageChangeListener {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
            mCurrentPosition = position;
            setTitle();
            PhotoView imageView = ((PhotoView) mPager.findViewWithTag(imageUrl.get(position)));
            if (imageView != null)
                imageView.reset();
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }
}
